package com.mall.service.impl;

import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.common.Const;
import com.mall.common.ServerResponse;
import com.mall.common.TokenCache;
import com.mall.dao.MmallUserMapper;
import com.mall.pojo.MmallUser;
import com.mall.service.IUserService;

@Service
public class UserServiceImpl implements IUserService{
	
	@Autowired
	private MmallUserMapper userMapper;
	
	@Override
	public MmallUser getUser(int id) {
		
		MmallUser user = userMapper.selectByPrimaryKey(id);
		
		return user;
	}

	@Override	//登录
	public ServerResponse<MmallUser> login(String username, String password) {
		
		int resultCount = userMapper.checkUserName(username);
		if(resultCount == 0){
			return ServerResponse.createByErrorMessage("用户名不存在");
		}
		
		String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
		MmallUser user = userMapper.selectLogin(username, md5Password);
		
		if(user == null){
			return ServerResponse.createByErrorMessage("密码错误");
		}
		
		return ServerResponse.createBySuccess("登录成功",user);
	}

	@Override 	//注册
	public ServerResponse<String> register(MmallUser user) {
		
		//检测用户名是否存在
		ServerResponse<String> response = this.checkValid(user.getUsername(),Const.USERNAME );
		if(!response.isSuccess()){
			return response;
		}
		
		//检测邮箱是否存在
		response = this.checkValid(user.getEmail(),Const.EMAIL);
		if(!response.isSuccess()){
			return response;
		}
		
		//设置角色 , 1位普通用户 , 0为管理员
		user.setRole(1);
		
		//密码md5加密
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		
		//设置注册时间
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		
		//执行插入
		int result = userMapper.insert(user);
		if(result == 0 ){
			return ServerResponse.createByErrorMessage("注册失败");
		}
		return ServerResponse.createBySuccessMessage("注册成功");
	}

	@Override	//检测用户名和邮箱
	public ServerResponse<String> checkValid(String str, String type) {
		
		if(StringUtils.isNotBlank("type")){
			
			//校验用户名
			if(Const.USERNAME.equals(type)){
				int result = userMapper.checkUserName(str);
				if(result > 0){
					return ServerResponse.createByErrorMessage("用户名已存在");
				}
			}
			
			//校验邮箱
			if(Const.EMAIL.equals(type)){
				int result = userMapper.checkEmail(str);
				if(result > 0){
					return ServerResponse.createByErrorMessage("邮箱已存在");
				}
			}
			
		}else{
			return ServerResponse.createByErrorMessage("参数错误");
		}
		
		return ServerResponse.createBySuccessMessage("校验成功");
	}

	@Override         // 通过用户名查询问题
	public ServerResponse selectQuestion(String username) {
		
		ServerResponse result = this.checkValid(username, Const.USERNAME);
		if(result.isSuccess()){
			//用户名不存在
			return ServerResponse.createByErrorMessage("用户名不存在");
		}
		
		String question = userMapper.selectQuestionByUsername(username);
		if(StringUtils.isNotBlank(question)){
			return ServerResponse.createBySuccess(question);
		}
		return ServerResponse.createByErrorMessage("找回密码的问题是空的");
	}

	@Override   //  通过用户名和问题查询 验证答案
	public ServerResponse<String> checkAnswer(String username, String question, String answer) {
		
		int result = userMapper.checkAnswer(username, question,answer);
		if(result > 0){
			//说明问题和答案是这个用户的,并且答案是正确的
			
			//将token存入缓存中
			String forgetToken = UUID.randomUUID().toString();
			TokenCache.setKey("token_"+username, forgetToken);
			
			return ServerResponse.createBySuccessMessage(forgetToken);
		}
		return ServerResponse.createByErrorMessage("问题答案错误");
	}
						
	@Override
	public ServerResponse<String> resetPassword(String username, String newPassword, String forgetToken) {
		
		//检测参数token是否传递过来
		if(StringUtils.isBlank(forgetToken)){
			return ServerResponse.createByErrorMessage("参数错误,token需要传递");
		}
		
		//校验用户名是否存在
		ServerResponse<String> result = this.checkValid(username, Const.USERNAME);
		if(result.isSuccess()){
			//用户名不存在
			return ServerResponse.createByErrorMessage("用户名不存在");
		}	
		//校验token是否过期
		String token = TokenCache.getKey("token_"+username);
		if(StringUtils.isBlank(token)){
			return ServerResponse.createByErrorMessage("token无效或者已过期");
		}
		
		if(StringUtils.equals(token, forgetToken)){
			
			String md5Password = DigestUtils.md5DigestAsHex(newPassword.getBytes());
			//执行更新操作
			int count = userMapper.updatePasswordByUsername(username,md5Password);
			if(count > 0 ){
				return ServerResponse.createBySuccessMessage("修改密码成功");
			}
		}else{
			return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
		}
		
		return ServerResponse.createByErrorMessage("更新密码失败");
	}

	@Override
	public ServerResponse<String> loginResetPassword(String oldPassword, String newPassword, MmallUser user) {
		
		//检验原密码是否正确
		int result = userMapper.checkPassword(DigestUtils.md5DigestAsHex(oldPassword.getBytes()),user.getId());
		if(result ==0 ){
			return ServerResponse.createByErrorMessage("原密码错误");
		}
		
		//重置密码
		user.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
		int count = userMapper.updateByPrimaryKeySelective(user);
		if(count == 0 ){
			return ServerResponse.createByErrorMessage("重置密码失败");
		}
		return ServerResponse.createBySuccessMessage("重置密码成功");
	
	}

	@Override
	public ServerResponse<MmallUser> updateInformation(MmallUser user) {
		
		//username是不能被更新的
		//校验email是否存在,可以不更新,此时email存在且是该用户的
		int result = userMapper.checkEmailByUserId(user.getId(),user.getEmail());
		if(result >0){
			return ServerResponse.createByErrorMessage("邮箱已存在,请更换email在尝试更新");
		}
		
		//赋值
		MmallUser nuser = new MmallUser();
		nuser.setId(user.getId());
		nuser.setPhone(user.getPhone());
		nuser.setQuestion(user.getQuestion());
		nuser.setAnswer(user.getAnswer());
		nuser.setEmail(user.getEmail());
		
		//更新
		int count = userMapper.updateByPrimaryKeySelective(nuser);
		if(count == 0){
			return ServerResponse.createByErrorMessage("更新个人信息失败");
		}
		
		return ServerResponse.createBySuccess("更新个人信息成功",nuser);
		
	}

	@Override
	public ServerResponse<MmallUser> getInformation(Integer id) {
		
		//通过id查询用户信息
		MmallUser user = userMapper.selectByPrimaryKey(id);
		if(user == null){
			return ServerResponse.createByErrorMessage("找不到当前用户");
		}
		return ServerResponse.createBySuccess(user);
	}
	
	//检验是否是管理员
	//角色0-管理员,1-普通用户'
	
	@Override
	public ServerResponse checkAdminRole(MmallUser user){
		if( user!=null && user.getRole().intValue() == 0 ){
			return ServerResponse.createBySuccess();
		}
		return ServerResponse.createByError();
		
	}
	
}
